import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/el_refresh.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/location/locationUtil.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/toast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wallet_utils/webview_common.dart';
import '../../agreement_dialog.dart';
import '../../home/api/home_api.dart';
import '../../home/bean/userAgreementBean.dart';
import '../../login_page/constant.dart';
import '../../mine/api/mine_api.dart';
import '../../mine/bean/aboutUsBean.dart';
import '../../mine/bean/productInfoBean.dart';
import '../../mine/contentType.dart';
import '../api/product_api.dart';
import '../bean/productBean.dart';
import 'state.dart';

class ProductPageLogic extends GetxController {
  final ProductPageState state = ProductPageState();
  List<ProductList>? productList=[];
  @override
  void onInit()  {
    super.onInit();
    EventBusUtils.getInstance().on<MsgEventBusUtils>().listen((event) {
      //是否显示产品状态
      if (event.type == MsgEventBusUtils.productStatus) {
        state.refreshController = RefreshController(initialRefresh: false);
        obtainProductInfoV2();
        productProgress();
      }
    });

    obtainProductInfoV2();
    productProgress();

  }

  void productProgress() async {

     int indexStatus= await LoginUtils.getIndexStatus();
    if(indexStatus==3 || indexStatus==4){
      getUser2WhereApi();
    }else{
      getUserInfo(ContentType.personalCredit);
    }
  }
  ///产品列表
  obtainProductInfoV2() {
    ProductApi.obtainProductInfoV2(BaseCallback(onSuccess: (map) {
      ProductBean productBean=ProductBean.fromJson(map);
      if(productBean.data!=null){
        productList=productBean.data?.productPageVO?.list;
        if(productList!.isNotEmpty  || productList!=null){
          state.loanAmount=productList![0].loanAmount;
          state.loanMinRate=productList![0].loanMinRate;
          state.linkUrl=productList![0].linkUrl;
          state.productId=productList![0].productId;
        }
      }
      refreshCompelet(state.refreshController);
      update();
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
        refreshCompelet(state.refreshController);
        update();
      });
    }));
  }

  //埋点
  void addLoanRecord(num productId, int showPage) async {

    HomeApi.addLoanRecord(
        productId,
        showPage,
        BaseCallback(
            onSuccess: (map) {},
            onError: (msg) {
              Future.delayed(const Duration(milliseconds: 500), () {
                ToastUtils.showToast(msg ?? "");
              });
            }));
  }
  void getUser2WhereApi() async {
    HomeApi.getUser2WhereApi(BaseCallback(onSuccess: (map) {
      UserAgreementBean userAgreementBean = UserAgreementBean.fromJson(map);
      if(userAgreementBean.data!=null){
        state.agreementContent= userAgreementBean.data?.content;

      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }
  void popover(int type,int index) {
    if(productList!.isNotEmpty){
      Future.delayed(Duration.zero, () {
        showDialog<Null>(
          context: Get.context!,
          barrierDismissible: false,
          useSafeArea: false,
          useRootNavigator: false,
          builder: (BuildContext context) {
            return AgreementDialog(
                name: '',
                content: state.agreementContent,
                submit: '我已阅读并同意授权',
                isClose: true,
                onTap: () {
                  Get.back();
                  if(type==1){
                    if(state.productId!=0){
                      addLoanRecord(state.productId!, ShowPage.list);
                    }
                    Get.to(WebViewCommon(
                      state.linkUrl ?? '',
                    ));
                  }else{
                    if(productList!.isNotEmpty){
                      addLoanRecord(productList![index].productId!, ShowPage.list);
                    }
                    Get.to(WebViewCommon(
                      productList![index].linkUrl ?? '',
                    ));
                  }
                });
          },
        );
      });
    }
  }
  //信用授权书
  getUserInfo(int type) {
    MineApi.getHTML(
        type,
        BaseCallback(onSuccess: (map) {
          AboutUsBean aboutUsBean = AboutUsBean.fromJson(map);
          if (aboutUsBean.data != null) {
            // state.agreementName = aboutUsBean.data?.name;
            state.agreementContent = aboutUsBean.data?.content;
            // Get.toNamed(BaseRouterConfig.agreement, arguments: {'name': name, 'content': content});
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }
}
